#include <iostream>
#include <string>
#include <functional>
#include <string>
#include <map>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <mutex>
#include <list>
#include <algorithm>
#include <memory>
#include <atomic>
#include <assert.h>

using namespace std;

typedef std::function<void*()> func_t;

/**
 * @brief The ClassFactory class            类工厂，负责根据字符串映射对应的类
 */
class ClassFactory
{
public:
    ~ClassFactory(){};

    //根据类注册时的名字, 创建类实例, 并返回
    void* getClassByName(std::string name)
    {
        std::map<std::string, func_t>::iterator it = my_map.find(name);
        if (it == my_map.end() )
        {
            return nullptr;
        }

        func_t fun = it->second;
        if (!fun)
        {
            return nullptr;
        }

        return fun();
    }

    //注册类名称与指针函数到映射关系
    void registClass(std::string name, func_t fun)
    {
        my_map[name] = fun;
    }

    //单例模式(静态局部变量方式实现单例)
    static ClassFactory& getInstance(){
        static ClassFactory fac;
        return fac;
    }

private:
    ClassFactory(){};  //私有
    // 禁止赋值
    ClassFactory &operator = (ClassFactory &cf) = delete;
    std::map<std::string, func_t> my_map;
};


class Test
{
public:
    Test(){ std::cout << "call Test Constructor fun" << std::endl; }
    ~Test(){ std::cout << "call Test Destructor fun" << std::endl; }
    void print()
    {
        const char* name = typeid(*this).name();

        while (*name >= '0' && *name <= '9') name++;
        std::cout << "call Test print fun - className: " << name << std::endl;
    }
};

void* create_Test()
{
    Test *t = new Test;
    return (t == NULL)? NULL:t;
}


int main()
{
    //注册指定的类
    ClassFactory::getInstance().registClass("Test", create_Test);

    //获取类对象
    Test *t = (Test*)ClassFactory::getInstance().getClassByName("Test");
    if ( t == nullptr )
    {
        std::cout << "get instnce Test err;" << std::endl;
        return 1;
    }

    // 打印
    t->print();

    delete t;
    t = nullptr;
    return 0;
}


